const { verifyToken, generateToken } = require("../utils/jwt");
const auth = (req, res, next) => {
    if (req.headers.authorization) {
        const token = req.headers.authorization.split(" ")[1] || "";
        if (verifyToken(token)) {
            // 重新设置token,保证其在操作过程中永远不会过期
            const username = verifyToken(token).username;
            res.header("Authorization", generateToken({ username }, "1h"));
            next();
        } else {
            return res.status(401).send({ code: 401, msg: "请先登录" });
        }
    } else {
        return res.status(401).send({ code: 401, msg: "请先登录" });
    }
};

module.exports = auth;
